package com.vvv.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vvv.constants.RedisConstant;
import com.vvv.mapper.CourseInfoMapper;
import com.vvv.model.dto.CourseQueryRequest;
import com.vvv.model.entity.CourseInfo;
import com.vvv.service.CourseInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author v
* @description 针对表【course_info(课表)】的数据库操作Service实现
* @createDate 2023-12-08 08:59:31
*/
@Service
public class CourseInfoServiceImpl extends ServiceImpl<CourseInfoMapper, CourseInfo>
    implements CourseInfoService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void startGrabbing() {
        List<CourseInfo> courseInfos = list().stream()
                .filter(courseInfo -> courseInfo.getLeftNum() > 0).collect(Collectors.toList());
        Map<String, String> map = new HashMap<>();
        for (CourseInfo courseInfo : courseInfos) {
            map.put(RedisConstant.STOCK_KEY + courseInfo.getId(), courseInfo.getLeftNum().toString());
        }
        stringRedisTemplate.opsForValue().multiSet(map);
    }

    @Override
    public Page<CourseInfo> listCourseByPage(CourseQueryRequest courseQueryRequest) {
        CourseInfo courseInfo = BeanUtil.copyProperties(courseQueryRequest, CourseInfo.class);
        long current = courseQueryRequest.getCurrent();
        long size = courseQueryRequest.getPageSize();
        String sortField = courseQueryRequest.getSortField();
        String sortOrder = courseQueryRequest.getSortOrder();
        QueryWrapper<CourseInfo> queryWrapper = new QueryWrapper<>(courseInfo);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals("ascend"), sortField);
        Page<CourseInfo> page = page(new Page<>(current, size), queryWrapper);
        return page;
    }
}




